package com.struct.graph.game
{
	import com.collection.AbilityCollection;
	import com.collection.DataWorkerCollection;
	import com.component.ComponentChildren;
	import com.struct.graph.game.body.BaseBody;
	import com.struct.graph.game.body.PlayerBody;
	
	import data.UserData;
	
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.utils.Dictionary;
	
	public class BattleFrame extends ComponentChildren
	{
		public var container:BattleContainer;//场景物体层
		
		private var skill:AbilityBox;
		public function BattleFrame()
		{
			super();
			
			var d:Dictionary = DataWorkerCollection.zip.data as Dictionary;
			
			var mapSource:BitmapData = d["mp"];
			width = mapSource.width;
			height = mapSource.height;
			
			graphics.beginBitmapFill(mapSource);
			graphics.drawRect(0, 0, width, height);
			graphics.endFill();
			
			container = new BattleContainer(width, height);
			addChild(container);
			
			var i:uint;
			var ab:AbilityBox;
			const abilitys:Array = AbilityCollection.abilitys;
			for(i = 0; i < 4; ++i){
				var info:Object = abilitys[i];
				ab = new AbilityBox(info);
				ab.x = 350 + i * (65 + 3);
				ab.y = 550;
				ab.addEventListener(MouseEvent.CLICK, skillHandler);
				addChild(ab);
				if(skill == null){
					skill = ab;
					skill.setSelected(true);
				}
			}
			
			container.skill = skill.d;
			var bodys:Array = [];
			//初始化建筑物体
			var bb:BaseBody;
			for(i = 0; i < 5; ++i){
				bb = new BaseBody(25, 500, 1, 1, 50000, d["0" + (Math.ceil(Math.random() * 3) + 1)] as BitmapData, 103, 79, 0.02, false, false);
				add2ValidatorCoincide(bb, bodys);
			}
			//初始化角色
			bb = new PlayerBody(UserData.name, 10, 100, 15, 10, 200, UserData.role, 64, 64, 0.02);
			add2ValidatorCoincide(bb, bodys);
			i = 1;
			for(var n:String in d){
				if(n.indexOf('a') == -1){
					continue;
				}
				bb = new PlayerBody("机器人" + i + "号", 10, 100, 15, 10, 200, d[n], 64, 64);
				add2ValidatorCoincide(bb, bodys);
				if(++i == 4){
					break;
				}
			}
			container.nextSoldier();
		}
		private function skillHandler(e:MouseEvent):void{
			skill.setSelected(false);
			skill = e.target as AbilityBox;
			skill.setSelected(true);
			container.skill = skill.d;
		}
		private function add2ValidatorCoincide(body:BaseBody, validator:Array):void{
			var mx:int = Math.random() * (width - 100) + 50;
			var my:int = Math.random() * (height - 100) + 50;
			
			var coincide:Boolean;
			for each(var o:Object in validator){
				var dist:Number = Math.sqrt(o.x*o.x + my*my);
				if(dist < o.radius + body.radius){
					coincide = true;
					break;
				}
			}
			if(coincide){
				add2ValidatorCoincide(body, validator);
			} else {
				validator.push({x: mx, y: my, radius: body.radius});
				body.x = mx;
				body.y = my;
				container.addBody(body);
			}
		}
	}
}